package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import model.Stock;
import util.DBUtil;

public class StockDAO {
	public boolean save(Stock stock){
		DBUtil util = new DBUtil("insert into stock values(?,?,?,?,?,?,?)");
		try {
			util.pst.setString(1, stock.getStockId());
			util.pst.setString(2, stock.getStockCode());
			util.pst.setString(3, stock.getQuantity()+"");
			util.pst.setString(4, stock.getStatus());
			util.pst.setString(5, stock.getCreator());
			util.pst.setString(6, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stock.getTs()));
			util.pst.setString(7, stock.getProductId());
			util.pst.execute();
			util.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			util.close();
			return false;
		}
	}
	public List<Stock> getByStatus(String status){
		List<Stock> stockList = new ArrayList<Stock>();
		DBUtil util = new DBUtil("select * from stock where status = ?");
		try {
			util.pst.setString(1, status);
			ResultSet rs = util.pst.executeQuery();
			while(rs.next()){
				Stock stock = new Stock(rs.getString(1),rs.getString(2),rs.getInt(3),rs.getString(4),rs.getString(5),rs.getDate(6),rs.getString(7));
				stockList.add(stock);
			}
			util.close();
		} catch (SQLException e) {
			e.printStackTrace();
			util.close();
		}
		return stockList;
	}
	public boolean updateStatus(String status,String stockId){
		DBUtil util = new DBUtil("update stock set STATUS = ? where STOCK_ID = ?");
		try {
			util.pst.setString(1, status);
			util.pst.setString(2, stockId);
			util.pst.execute();
			util.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			util.close();
			return false;
		}
	}
	public boolean updateCodeAndCreator(String code,String creator,String id){
		DBUtil util = new DBUtil("update stock set STOCK_CODE = ?,CREATOR = ? where STOCK_ID = ?");
		try {
			util.pst.setString(1, code);
			util.pst.setString(2, creator);
			util.pst.setString(3, id);
			util.pst.execute();
			util.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			util.close();
			return false;
		}
	}
}
